let ue = UE.getEditor("remark")
$(function () {
    jeDate("#beginTime", {
        format: "YYYY-MM-DD hh:MM",
        minDate: getSysDate(),
        isinitVal: true
    });
    jeDate("#endTime", {
        format: "YYYY-MM-DD hh:MM",
        minDate: getSysDate()
    });
    jeDate("#beginTimeQuery", {
        format: "YYYY-MM-DD"
    });
    jeDate("#endTimeQuery", {
        format: "YYYY-MM-DD"
    });
    query();
    $(".js-simple-query").unbind("click").click(function () {
        $("#myTable").bootstrapTable("refresh");
    })
    $(".js-auto-select").each(function () {
        var module = $(this).attr("module");
        createAutoSelect(module);
    })
    $("#sortId").unbind("click").click(function (e) {
        e.stopPropagation();
        $("#menuContent").css({
            "width": $(this).outerWidth() + "px"
        }).slideDown(200);
    });
    $("body").unbind("click").click(function () {
        $("#menuContent").hide();
    });
    $("#menuContent").unbind("click").click(function (e) {
        e.stopPropagation();
    });
    $.ajax({
        url: "/ret/examget/getexamTestSortTree",
        type: "post",
        dataType: "json",
        success: function (data) {
            $.fn.zTree.init($("#menuTree"), setting1, data);
        }
    });
    getExamQuestionRecordForSelect();
})

function query() {
    $("#myTable").bootstrapTable({
        url: '/ret/examget/getExamTestManageList',
        method: 'post',
        contentType: 'application/x-www-form-urlencoded',
        toolbar: '#toobar',//工具列
        striped: true,//隔行换色
        cache: false,//禁用缓存
        pagination: true,//启动分页
        sidePagination: 'server',//分页方式
        pageNumber: 1,//初始化table时显示的页码
        pageSize: 10,//每页条目
        showFooter: false,//是否显示列脚
        showPaginationSwitch: true,//是否显示 数据条数选择框
        sortable: true,//排序
        search: true,//启用搜索
        sortOrder: "asc",
        showColumns: true,//是否显示 内容列下拉框
        showRefresh: true,//显示刷新按钮
        idField: 'recordId',//key值栏位
        clickToSelect: true,//点击选中checkbox
        pageList: [10, 20, 30, 50],//可选择单页记录数
        queryParams: queryParams,
        columns: [{
            checkbox: true
        }, {
            field: 'num',
            title: '序号',//标题  可不加
            width: '50px',
            formatter: function (value, row, index) {
                return index + 1;
            }
        }, {
            field: 'title',
            title: '考试标题',
            width: '200px',
            formatter:function (value,row,index)
            {
                return "<a href=\"javascript:void(0);details('" + row.recordId + "')\" style='cursor: pointer'>"+value+"</a>";
            }
        }, {
            field: 'questionTitle',
            title: '试卷标题',
            width: '150px',
            formatter: function (value, row, index) {
                return "《" + value + "》";
            }
        }, {
            field: 'deptId',
            width: '80px',
            title: '主考部门',
            formatter: function (value, row, index) {
                return getDeptNameByDeptIds(value);
            }
        }, {
            field: 'sortName',
            width: '80px',
            title: '试卷分类'
        }, {
            field: 'isOpen',
            title: '是否开卷',
            width: '50px',
            formatter: function (value, row, index) {
                if (value == "1") {
                    return "是";
                } else {
                    return "否";
                }
            }
        }, {
            field: 'beginTime',
            width: '100px',
            title: '开始时间'
        }, {
            field: 'endTime',
            title: '结束时间',
            width: '100px'
        }, {
            field: 'status',
            title: '状态',
            width: '50px',
            formatter: function (value, row, index) {
                if (value == "0") {
                    return "开考";
                } else if (value == "1") {
                    return "结束"
                } else {
                    return "未知";
                }
            }
        }, {
            field: 'duration',
            width: '50px',
            title: '考试时长',
            formatter: function (value, row, index) {
                return value + "分钟";
            }
        }, {
            field: 'opt',
            title: '操作',
            align: 'center',
            width: '100px',
            formatter: function (value, row, index) {
                return createOptBtn(row.recordId, row.status);
            }
        }],
        onClickCell: function (field, value, row, $element) {
            //alert(row.SystemDesc);
        },
        responseHandler: function (res) {
            if (res.status == "500") {
                console.log(res.msg);
            } else if (res.status == "100") {
                layer.msg(sysmsg[res.msg]);
            } else {
                return {
                    total: res.list.total, //总页数,前面的key必须为"total"
                    rows: res.list.list
                    //行数据，前面的key要与之前设置的dataField的值一致.
                };
            }
        }
    });
}

function queryParams(params) {
    let temp = {
        search: params.search,
        pageSize: this.pageSize,
        pageNumber: this.pageNumber,
        sort: params.sort,
        sortOrder: params.order,
        endTime: $("#endTimeQuery").val(),
        beginTime: $("#beginTimeQuery").val()
    };
    return temp;
};

function createOptBtn(recordId, status) {
    let html = "<a href=\"javascript:void(0);edit('" + recordId + "')\" class=\"btn btn-primary btn-xs\">编辑</a>&nbsp;&nbsp;"
        + "<a href=\"javascript:void(0);deleteReocrd('" + recordId + "')\" class=\"btn btn-darkorange btn-xs\" >删除</a>&nbsp;&nbsp;";
    if (status == "1") {
        html += "<a href=\"javascript:void(0);setRecordStatus('" + recordId + "','0')\" class=\"btn btn-success btn-xs\" >开考</a>";
    } else {
        html += "<a href=\"javascript:void(0);setRecordStatus('" + recordId + "','1')\" class=\"btn btn-purple btn-xs\" >结束</a>";
    }
    return html;
}

function setRecordStatus(recordId, status) {
    $.ajax({
        url: "/set/examset/updateExamTest",
        type: "post",
        dataType: "json",
        data: {
            recordId: recordId,
            status: status
        },
        success: function (data) {
            if (data.status == "500") {
                console.log(data.msg);
            } else if (data.status == "100") {
                layer.msg(sysmsg[data.msg]);
            } else {
                layer.msg(sysmsg[data.msg]);
                $("#myTable").bootstrapTable("refresh");
            }
        }
    })
}

function deleteReocrd(recordId) {
    if (confirm("确定删除试卷记录吗？")) {
        $.ajax({
            url: "/set/examset/deleteExamTest",
            type: "post",
            dataType: "json",
            data: {recordId: recordId},
            success: function (data) {
                if (data.status == "200") {
                    layer.msg(sysmsg[data.msg]);
                    $("#myTable").bootstrapTable("refresh");
                } else if (data.status == "100") {
                    layer.msg(sysmsg[data.msg]);
                } else {
                    console.log(data.msg);
                }
            }
        });
    }
}

function edit(recordId) {
    $("#listdiv").hide();
    $("#infodiv").show();
    $("#show_attach").empty();
    $("#attach").attr("data_value", "");
    $("#deptId").attr("data-value", "");
    $("#userPriv").attr("data-value", "");
    $("#deptPriv").attr("data-value", "");
    $("#levelPriv").attr("data-value", "");
    $("#sortId").attr("data-value", "");
    ue.setContent()("");
    document.getElementById("form1").reset();
    $(".js-back-btn").unbind("click").click(function () {
        goback();
    })
    $.ajax({
        url: "/ret/examget/getExamTestById",
        type: "post",
        dataType: "json",
        data: {recordId: recordId},
        success: function (data) {
            if (data.status == "200") {
                let info = data.list;
                for (let id in info) {
                    if (id == "attach") {
                        $("#show_attach").html("");
                        $("#attach").attr("data_value", info.attach);
                        createAttach("attach", 4);
                    } else if (id == "deptId") {
                        $("#" + id).attr("data-value", info[id]);
                        $("#" + id).val(getDeptNameByDeptIds(info[id]));
                    } else if (id == "userPriv") {
                        $("#" + id).attr("data-value", info[id]);
                        $("#" + id).val(getUserNameByStr(info[id]));
                    } else if (id == "deptPriv") {
                        $("#" + id).attr("data-value", info[id]);
                        $("#" + id).val(getDeptNameByDeptIds(info[id]));
                    } else if (id == "levelPriv") {
                        $("#" + id).attr("data-value", info[id]);
                        $("#" + id).val(getUserLevelStr(info[id]));
                    } else if (id == "isOpen") {
                        $("input:checkbox[name='isOpen'][value='" + info[id] + "']").attr("checked", "checked");
                    } else if (id == "sortId") {
                        $("#" + id).attr("data-value", info[id]);
                        $.ajax({
                            url: "/ret/examget/getExamTestSortById",
                            type: "post",
                            dataType: "json",
                            async: false,
                            data: {
                                sortId: info[id]
                            },
                            success: function (res) {
                                if (data.status == "200") {
                                    $("#" + id).val(res.list.sortName);
                                } else if (res.status == "100") {
                                    layer.msg(sysmsg[res.msg]);
                                } else {
                                    console.log(res.msg);
                                }

                            }
                        });
                    } else if (id == "remark") {
                        $("#remark").code(info[id]);
                    } else {
                        $("#" + id).val(info[id]);
                    }
                }
                $(".js-update-save").unbind("click").click(function () {
                    updateExamTest(recordId);
                })
            } else if (data.status == "100") {
                layer.msg(sysmsg[data.msg]);
            } else if (data.status == "500") {
                console.log(data.msg);
            }
        }
    })
}

function details(recordId) {
    window.open("/app/core/exam/examtestdetails?recordId=" + recordId);
}

function updateExamTest(recordId) {
    $.ajax({
        url: "/set/examset/updateExamTest",
        type: "post",
        dataType: "json",
        data: {
            recordId: recordId,
            sortNo: $("#sortNo").val(),
            title: $("#title").val(),
            questionRecordId: $("#questionRecordId").val(),
            isOpen: getCheckBoxValue("isOpen"),
            deptId: $("#deptId").attr("data-value"),
            sortId: $("#sortId").attr("data-value"),
            userPriv: $("#userPriv").attr("data-value"),
            deptPriv: $("#userPriv").attr("data-value"),
            levelPriv: $("#levelPriv").attr("data-value"),
            beginTime: $("#beginTime").val(),
            endTime: $("#endTime").val(),
            duration: $("#duration").val(),
            passMark: $("#passMark").val(),
            attach: $("#attach").attr("data_value"),
            remark: $("#remark").code()
        },
        success: function (data) {
            if (data.status == "200") {
                layer.msg(sysmsg[data.msg]);
                location.reload();
            } else if (data.status == "100") {
                layer.msg(sysmsg[data.msg]);
            } else if (data.status == "500") {
                console.log(data.msg);
            }
        }
    })
}

function goback() {
    $("#infodiv").hide();
    $("#listdiv").show();
}

let setting1 = {
    async: {
        enable: true,// 设置 zTree 是否开启异步加载模式
        url: "/ret/examget/getexamTestSortTree",// Ajax 获取数据的 URL 地址
        autoParam: ["sortId"],// 异步加载时需要自动提交父节点属性的参数
    },
    view: {
        dblClickExpand: false,
        selectedMulti: false
        //禁止多选
    },
    data: {
        simpleData: {
            enable: true,
            idKey: "sortId",
            pIdKey: "levelId",
            rootPId: "0"
        },
        key: {
            name: "sortName"
        }
    },
    callback: {
        onClick: function (e, treeId, treeNode) {
            var zTree = $.fn.zTree.getZTreeObj("menuTree"), nodes = zTree.getSelectedNodes(), v = "";
            vid = "";
            nodes.sort(function compare(a, b) {
                return a.id - b.id;
            });
            for (var i = 0, l = nodes.length; i < l; i++) {
                v += nodes[i].sortName + ",";
                vid += nodes[i].sortId + ",";
            }
            if (v.length > 0)
                v = v.substring(0, v.length - 1);
            if (vid.length > 0)
                vid = vid.substring(0, vid.length - 1);
            var idem = $("#sortId");
            idem.attr("data-value", vid);
            idem.val(v);
        }
    }
};

function getExamQuestionRecordForSelect() {
    $.ajax({
        url: "/ret/examget/getExamQuestionRecordForSelect",
        type: "post",
        dataType: "json",
        success: function (data) {
            if (data.status == "200") {
                for (let i = 0; i < data.list.length; i++) {
                    $("#questionRecordId").append("<option value='" + data.list[i].recordId + "'>" + data.list[i].title + "</option>")
                }
            } else if (data.status == "500") {
                console.log(data.msg);
            } else {
                layer.msg(sysmsg[data.msg]);
            }
        }
    });
}
